# -*- coding: utf-8 -*-

from script_utils import query, get_one2list, oid2nid, get_one2dict
from script_utils import models
import json


def migrate_classify():
    cols = [
            "id",
            "name",
            "name_en",
            "is_active",
            "date_added",
            ]

    for row in query('vacation_classify', cols=cols):
        obj = dict(zip(cols, row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_classify"][oid]
        models.Classify(**obj).save()


def migrate_supplier():
    cols = [
            "id",
            "name",
            "name_en",
            "address",
            "contacts",
            "emails",
            "book_tels",
            "customer_tels",
            "logo",
            "pay_account_number",
            "pay_bank",
            "pay_name",
            "bank_tel",
            "bank_address",
            "swift_code",
            "routing_number",
            "remark",
            "user_id",
            "last_modified",
            "date_added",
            ]

    supplier_id2destination_ids = get_one2list('vacation_supplierdestination', 'supplier_id', 'destination_id')
    for row in query('vacation_supplier', cols=cols):
        obj = dict(zip(cols, row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_supplier"][oid]
        obj['destinations'] = [oid2nid["vacation_destination"][destination_id] for destination_id in supplier_id2destination_ids.get(oid, [])]
        models.Supplier(**obj).save()


def migrate_productsku():
    cols = [
            "id",
            "product_id",
            "name",
            "name_en",
            "start_date",
            "end_date",
            "week_binary",
            # "blackoutdate",  # 在表vacation_producttypeblackoutdate
            "fee",
            "adult_fee",
            "adult_retail_fee",
            # "adult_quotation",  # 在表vacation_supplierproducttype
            "description",
            "child_fee",
            "child_retail_fee",
            # "child_quotation",  # 在表vacation_supplierproducttype
            "child_description",
            "is_adult",
            "is_default",
            "currency",
            # "quotation_currency",  # 在表vacation_supplierproducttype
            ]

    blackoutdate_typeid_to_dates = {}
    producttypeblackoutdate_cols = ['type_id', 'date', 'is_active']
    for row in query('vacation_producttypeblackoutdate', cols=producttypeblackoutdate_cols):
        obj = dict(zip(producttypeblackoutdate_cols, row))
        if obj['is_active'] == True:
            blackoutdate_typeid_to_dates.setdefault(obj['type_id'], []).append(obj['date'])

    typeid_to_dict = get_one2dict('vacation_supplierproducttype', ["type_id", "null_quotation", "adult_quotation", "child_quotation", "currency"], "type_id")
    for row in query('vacation_producttype', cols=cols):
        obj = dict(zip(cols, row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_producttype"][oid]
        obj['blackoutdate'] = blackoutdate_typeid_to_dates.get(oid, [])

        supplierproducttype_info = typeid_to_dict.get(oid, {})
        if supplierproducttype_info:
            obj['adult_quotation'] = supplierproducttype_info['adult_quotation'] or supplierproducttype_info['null_quotation']
            obj['child_quotation'] = supplierproducttype_info['child_quotation']
            obj['currency'] = supplierproducttype_info['currency']

        obj['product'] = oid2nid["vacation_product"][obj['product_id']]
        del obj['product_id']
        models.ProductSKU(**obj).save()


def migrate_product():
    cols = {
        'vacation_product': [
            "id",
            "last_modified",
            "date_added",
            "is_active",
            "published",
            "is_push",
            "name",
            "name_en",
            "category_id",
            "destination_id",
            "cover",
            "photos",
            "address",
            "description",
            "open_time",
            "service_language",
            "arrival_type",
            "time_consuming_min",
            "time_consuming_max",
            "currency",
            "fee",
            # "retail_fee",  #??
            "outline",
            "supplier_id",
            "remark",

            "st_asgeojson(st_astext(location))",

            "classify_id",
            "tour_inclusions",
            "tour_exclusions",
            "remind",
            "usage_method",
            "start_delta",
            "start_time",
            "close_date",
            "cancel_hours",
            "baby_description",
            "pick_range",
            "is_paper_voucher",
            "is_sell_on_request",
            "request_hours",
            # "product_display_info",
            "base_info",
            "price_info",
            "travel_time",
            "agreement",
            # "productskus",
            # "supplier_confirm_option",
            # "product_custom_category",
        ],
        'vacation_producttype': [],
        'vacation_productcustomfield': [],
        'vacation_supplierconfirmoption': [
            'product_id',
            'name',
            'is_active'
        ],
        'vacation_productcustomcategory': [
            "product_id",
            "option_type",
            "display_name",
            "attribute_name",
            "attribute_value",
            "text_hint",
            "is_active",
            "category"
        ]
    }

    product_id2producttype_ids = get_one2list('vacation_producttype', 'product_id', 'id')

    product_id2supplierconfirmoptions = {}
    for row in query('vacation_supplierconfirmoption', cols=cols['vacation_supplierconfirmoption']):
        obj = dict(zip(cols['vacation_supplierconfirmoption'], row))
        if obj['is_active'] == True:
            product_id2supplierconfirmoptions.setdefault(obj['product_id'], []).append(obj['name'])

    customcategory_groupby_productid = {}
    for row in query('vacation_productcustomcategory', cols=cols['vacation_productcustomcategory']):
        obj = dict(zip(cols['vacation_productcustomcategory'], row))
        if obj['is_active'] == True:
            obj['product_id'] = oid2nid["vacation_product"][obj['product_id']]
            customcategory_groupby_productid.setdefault(obj['product_id'], []).append(obj)

    for row in query('vacation_product', cols=cols['vacation_product']):
        obj = dict(zip(cols['vacation_product'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_product"][oid]
        obj['productskus'] = [oid2nid["vacation_producttype"][x] for x in product_id2producttype_ids.get(oid, [])]

        base_info, price_info, travel_time, agreement = obj["base_info"], obj["price_info"], obj["travel_time"], obj["agreement"]
        obj['product_display_info'] = {
                    "base_info": base_info or '',
                    "price_info": price_info or '',
                    "travel_time": travel_time or '',
                    "agreement": agreement or '',
        }

        obj['supplier_confirm_option'] = product_id2supplierconfirmoptions.get(oid, [])

        obj['product_custom_category'] = {
              'basic': [],  # 基本信息
              'extended': [],  # 备注/扩展信息
              'contact': [],  # 联系人信息
              "is_baby": False,
              "use_days": False
        }

        customcategorys = customcategory_groupby_productid.get(oid, [])
        for customcategory in customcategorys:
            obj['product_custom_category'][customcategory['category']].append(customcategory)
            if customcategory['attribute_name'] == 'baby_count':
                obj['product_custom_category']['is_baby'] = True
            if customcategory['attribute_name'] == 'use_days':
                obj['product_custom_category']['use_days'] = True

        obj['start_time'] = str(obj['start_time'])  # mongodb没有time类型，用StringField

        obj['location'] = obj['st_asgeojson(st_astext(location))'] and json.loads(obj['st_asgeojson(st_astext(location))'])["coordinates"]

        obj['destination'] = obj['destination_id'] and oid2nid["vacation_destination"][obj['destination_id']]
        obj['supplier'] = obj['supplier_id'] and oid2nid["vacation_supplier"][obj['supplier_id']]
        obj['classify'] = obj['classify_id'] and oid2nid["vacation_classify"][obj['classify_id']]

        del obj["base_info"]
        del obj["price_info"]
        del obj["travel_time"]
        del obj["agreement"]
        del obj['st_asgeojson(st_astext(location))']
        del obj['destination_id']
        del obj['supplier_id']
        del obj['classify_id']

        models.Product(**obj).save()


if __name__ == '__main__':
    # migrate_classify()
    # migrate_supplier()
    # migrate_productsku()
    migrate_product()
